package com.xyh.flowershop.service.impl;

import com.xyh.flowershop.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 小约翰可汗
 * @className FileServiceImpl
 * @createTime 2024/3/3115:40
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Value("${file.avatar-path}")
    private String avatarBasePath;

    @Value("${file.type-path}")
    private String typeBasePath;

    @Value("${file.goods-path}")
    private String goodsBasePath;

    @Value("${file.swipers-path}")
    private String swiperBasePath;

    @Value("${file.path}")
    private String basePath;


    /**
     * 文件上传
     * @return
     */
    @Override
    public String uploadFile(MultipartFile file , String reqPath) {
        String imgName = file.getOriginalFilename();
        String type = imgName.substring(imgName.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + type;
        String dirPath = dirPath(reqPath);
        String path = dirPath + fileName;
        File dir = new File(dirPath);
        if(!dir.exists()){
            dir.mkdir();
        }
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    private String dirPath(String reqPath){
        if(reqPath.contains("type")){
            return typeBasePath;
        }
        if(reqPath.contains("avatar")){
            return avatarBasePath;
        }
        if(reqPath.contains("swiper")){
            return swiperBasePath;
        }
        if(reqPath.contains("goods")){
            return goodsBasePath;
        }
        return basePath;
    }
}
